# Copyright (c) 2017 Presto Labs Pte. Ltd.
# Author: jaewon

import functools
import platform
import urllib.error
import urllib.request


@functools.lru_cache(maxsize=1)
def query_ec2_region():
  try:
    zone_url = ('http://169.254.169.254/latest/meta-data/placement/' 'availability-zone')
    with urllib.request.urlopen(zone_url) as f:
      return f.read().decode('ascii').strip()
  except urllib.error.HTTPError:
    raise ValueError()


@functools.lru_cache(maxsize=1)
def get_hostname():
  return platform.node()


@functools.lru_cache(maxsize=1)
def get_region_or_fqdn():
  try:
    return query_ec2_region()
  except ValueError:
    return get_hostname()
